<template>
  <div>
    <el-upload
      class="uploader"
      :multiple="multiple"
      :action="action"
      :list-type="listType"
      :file-list="fileList"
      :on-preview="preview ? handlePreview : null"
      :on-success="handleUploadSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :disabled="disabled"
      :limit="limit"
      :data="data"
      :on-exceed="onExceed"
      :class="{'upload-fulled' : fileList.length >= limit}"
    >
      <i v-if="!$slots.default" class="el-icon-plus"></i>
      <slot/>
    </el-upload>
    <img-preview-dialog :url="previewImage" :visible.sync="isShow"/>
  </div>
</template>

<script>
import ImgPreviewDialog from './previewDialog'
import emitter from 'element-ui/src/mixins/emitter';

export default {
  name: "image-upload",
  props: {
    value: {type: Array | String},
    action: {type: String, default: process.env.VUE_APP_BASE_API + '/web/imgUploading?folderName=shop/img/'},
    limit: {type: Number, default: 1},
    maxSize: {type: Number, default: 0},
    multiple: {type: Boolean, default: false},
    disabled: {type: Boolean, default: false},
    listType: {type: String, default: 'picture-card'},
    preview: {type: Boolean, default: true},
    data: {
      type: Object, default: () => {
      }
    }
  },
  mixins: [emitter],
  data() {
    return {
      valueType: 'string',
      fileList: [],
      isShow: false,
      previewImage: '',
    }
  },
  methods: {
    emitInput() {
      setTimeout(() => {
        let value = [];
        this.fileList.forEach(item => {
          if (item.status == "success") {
            // 兼容回显时的 item.url
            value.push(item.response ? item.response.data.filePath : item.url);
          }
        });
        value = value.join(',');
        this.$emit('input', value);
        this.dispatch('ElFormItem', 'el.form.blur', value);
        this.dispatch('ElFormItem', 'el.form.change', value);
      }, 1000)
    },
    handlePreview(file) {
      this.previewImage = file.url;
      this.isShow = true;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.$emit('remove');
      this.emitInput()
    },
    handleUploadSuccess(res, file, fileList) {
      if (res && res.code === 200) {
        this.fileList = fileList;
        this.emitInput();
        this.$emit('success', res.data);
      } else {
        fileList.forEach(function (item, index) {
          if (item === file) {
            fileList.splice(index, 1)
          }
        });
        this.$message.error(res.message || '文件上传失败');
        this.$emit('fail')
      }
      this.$emit('complete')
    },
    uploadError(fileList = [], file) {
      if (!fileList) {
        return false;
      }
      fileList.forEach(function (item, index) {
        if (item === file) {
          fileList.splice(index, 1)
        }
      });
      this.$emit('fail');
      return false;
    },
    beforeUpload(file) {
      let imgTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
      let size = file.size;
      if (imgTypes.indexOf(file.type) < 0) {
        this.$message.error('只能上传 png、jpg、jpeg或gif类型的图片');
        return false;
      }
      if (this.maxSize > 0 && size > this.maxSize * 1024 * 1024) {
        this.$message.error(`上传的图片不能大于${this.maxSize}M`);
        return false;
      }
      this.$emit('before')
    },
    onExceed() {
      this.$message.warning(`最多只能上传${this.limit}张图片`)
    },
    handleChange(file) {
      this.$emit('change', file);
    },
    handleError() {
      this.$emit('error');
      this.$emit('complete')
    },
    initFileList() {

      let value = [];
      if (typeof this.value === 'string') {
        this.valueType = 'string';
        if (this.value) {
          value = this.value.split(',')
        }
      } else {
        this.valueType = 'array';
        value = this.value || [];
      }
      this.fileList.forEach((item, index) => {
        if (!value[index]) {
          this.fileList.splice(index, 1)
        } else {
          if (value[index] != item.url) {
            this.fileList[index].url = value[index];
          }
        }
      });
      // this.fileList = [];
      value.forEach((item, index) => {
        if (this.fileList[index] && this.fileList[index].url == item) return;
        this.fileList.push({
          url: item
        })
      })
    }
  },
  created() {
    this.initFileList()
  },
  watch: {
    value(val) {
      this.initFileList()
    }
  },
  components: {
    ImgPreviewDialog
  }
}
</script>

<style>
.upload-fulled .el-upload--picture-card {
  display: none;
}

.el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

.el-upload-list--picture-card {
  line-height: 0;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
}
</style>

<style scoped>
</style>
